package com.sunreal.paygateway.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sunreal.paygateway.dao.mapper.MchInfoMapper;
import com.sunreal.paygateway.dao.mapper.PayChannelMapper;
import com.sunreal.paygateway.dao.mapper.PayOrderMapper;
import com.sunreal.paygateway.dao.mapper.RefundOrderMapper;
import com.sunreal.paygateway.dao.model.MchInfo;
import com.sunreal.paygateway.dao.model.PayChannel;
import com.sunreal.paygateway.dao.model.PayOrder;

/**
 * 功能描述：常用、基础Service实现类
 *
 * @Author 彭广
 * @Date 2019/4/16
 */
@Service
public class BaseService {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private MchInfoMapper mchInfoMapper;

    @Autowired
    private PayChannelMapper payChannelMapper;

    @Autowired
    private RefundOrderMapper refundOrderMapper;

    /**
     * 根据主键查询商户信息
     *
     * @param mchId 商户ID
     * @return 商户信息
     */
    public MchInfo baseSelectMchInfo(String mchId) {
        return mchInfoMapper.selectByPrimaryKey(mchId);
    }

    /**
     * 插入订单信息
     * @param payOrder 订单信息
     * @return 插入条数
     */
    public int baseCreatePayOrder(PayOrder payOrder) {
        return payOrderMapper.insertSelective(payOrder);
    }

    /**
     * 根据订单ID查询订单信息
     * @param payOrderId 订单ID
     * @return 订单信息
     */
    public PayOrder baseSelectPayOrder(String payOrderId) {
        return payOrderMapper.selectByPrimaryKey(payOrderId);
    }

    /**
     * 根据商户ID和商户订单号查询订单信息
     * @param mchId
     * @param mchOrderNo
     * @return
     */
    public PayOrder baseSelectPayOrderByMchIdAndMchOrderNo(String mchId, String mchOrderNo) {
        return payOrderMapper.selectByMchIdAndMchOrderNo(mchId,mchOrderNo);
    }

    /**
     * 根据商户ID和支付渠道查询 支付渠道信息
     * @param mchId  商户ID
     * @param channelId 支付渠道
     * @return 支付渠道信息
     */
    public PayChannel baseSelectPayChannelByMchIdAndChannelId(String mchId, String channelId) {
        return payChannelMapper.selectByMchIdAndChannelId(mchId, channelId) ;
    }

    /**
     * 根据订单ID更新订单状态
     * @param payOrderId     支付中心订单号
     * @param channelOrderNo 渠道订单号（微信、蚂蚁金服返回的订单号）
     * @param status         订单状态
     * @return  更新条数
     */
    protected int baseUpdateStatus4Ing(String payOrderId, Byte status, String channelOrderNo) {
        PayOrder payOrder = new PayOrder();
        payOrder.setStatus(status);
        if(channelOrderNo != null) payOrder.setChannelorderno(channelOrderNo);
        payOrder.setPaysucctime(System.currentTimeMillis());
        payOrder.setPayorderid(payOrderId);
        return payOrderMapper.updateByPrimaryKeySelective(payOrder);
    }
}
